package com.lam.code.utils;

import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lam
 * @description Servlet工具类
 * @date 2019/10/24 22:31
 */
public class ServletUtil extends cn.hutool.extra.servlet.ServletUtil {
    private static final String SPEC_STR_REQUEST_ACCEPT = "accept";
    private static final String SPEC_STR_REQUESTED_WITH = "X-Requested-With";
    private static final String SPEC_STR_XML_HTTP_REQUEST = "XMLHttpRequest";
    private static final String SPEC_STR_APP_JSON = "application/json";
    private static final String SPEC_STR_SUFFIX_JSON = ".json";
    private static final String SPEC_STR_SUFFIX_XML = ".xml";
    private static final String SPEC_STR_PRE_AJAX = "__ajax";
    private static final String SPEC_STR_JSON = "json";
    private static final String SPEC_STR_XML = "xml";

    /**
     * 是否是Ajax异步请求
     *
     * @param request 请求对象
     */
    public static boolean isAjaxRequest(HttpServletRequest request)
    {
        String accept = request.getHeader(SPEC_STR_REQUEST_ACCEPT);
        if (accept != null && accept.contains(SPEC_STR_APP_JSON))
        {
            return true;
        }

        String xRequestedWith = request.getHeader(SPEC_STR_REQUESTED_WITH);
        if (xRequestedWith != null && StrUtil.containsAnyIgnoreCase(xRequestedWith,SPEC_STR_XML_HTTP_REQUEST))
        {
            return true;
        }

        if (StrUtil.containsAnyIgnoreCase(request.getRequestURI(), SPEC_STR_SUFFIX_JSON, SPEC_STR_SUFFIX_XML))
        {
            return true;
        }

        if (StrUtil.containsAnyIgnoreCase(request.getParameter(SPEC_STR_PRE_AJAX), SPEC_STR_JSON, SPEC_STR_XML))
        {
            return true;
        }
        return false;
    }

}
